set more off

use dataset, clear

*** impute pres vote for non-election years ***

drop if year > 2012
gsort town -year 
foreach x in demvoteshare totalvotes lagdemvoteshare {
	bys town: replace `x' = `x'[_n-1] if mi(`x') & year >= 1990 & year <= 2012
}
xtset townid year

*** residualize ***

gen y = demvoteshare
reg y lagdemvoteshare i.year [aw=totalvotes] , a(town)
predict e, res
drop y
rename e y 

***

local reps 500

gen index = _n
foreach k in 1 2 {
gen B`k' = .
gen UB`k' = .
gen LB`k' = .
gen SE`k' = .
}

foreach k in 1 2 {
	foreach c in 1 5 10 15 20 25 30 35 40 45 50 {
		preserve
			keep if abs(X) <= `c'/100
			su y
			xtset, clear
			di `c'/100
			if `k' == 1 bootstrap, cl(town) reps(`reps'): reg y Z i.Z##c.X
			if `k' == 2 bootstrap, cl(town) reps(`reps'): reg y Z i.Z##c.X##c.X
			
		restore
		replace B`k' = _b[Z] if index == `c'
		replace SE`k' = _se[Z] if index == `c'
		replace UB`k' = _b[Z] + 1.96*_se[Z] if index == `c'
		replace LB`k' = _b[Z] - 1.96*_se[Z] if index == `c'
	}
}

keep if !mi(B1)

foreach k in 1 2 {

	if `k' == 1 local mytitle "Linear"
	if `k' == 2 local mytitle "Quadratic"
	
	#delimit;

	gr tw
		(sc B`k' index, col(black))
		(rspike UB`k' LB`k' index, col(black))
		,
			legend(off)
			plotregion(style(none))
			ylab(, angle(horiz))
			xscale(reverse)
			yline(0)
			name(g`k', replace)
			title(`mytitle')
			;
			
	#delimit cr

}

gr combine g1 g2, cols(2)

gr export "figure A5.eps", replace
